from qcloud_cos import CosS3Client
from qcloud_cos import CosConfig
from django.conf import settings
from qcloud_cos.cos_exception import CosServiceError


# 创建桶
def create_bucket(bucket, region):
    secret_id = settings.COS_SECRET_ID  # 替换为用户的 secretId
    secret_key = settings.COS_SECRET_KEY  # 替换为用户的 secretKey

    config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key)
    # 2. 获取客户端对象
    client = CosS3Client(config)

    client.create_bucket(
        Bucket=bucket,
        ACL="public-read",  # private/ public-read/ public-read-write

    )
    # 设置跨域
    cors_config = {
        'CORSRule': [
            {
                'AllowedOrigin': '*',
                'AllowedMethod': ['PUT', 'GET', 'HEAD', 'DELETE'],
                'AllowedHeader': '*',
                'AllowedSeconds': 500
            }
        ]
    }
    client.put_bucket_cors(
        Bucket=bucket,
        CORSConfiguration=cors_config
    )


# 上传文件
def upload_file(bucket, region, file_object, key):
    secret_id = settings.COS_SECRET_ID  # 替换为用户的 secretId
    secret_key = settings.COS_SECRET_KEY  # 替换为用户的 secretKey

    config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key)
    # 2. 获取客户端对象
    client = CosS3Client(config)

    #  上传文件
    response = client.upload_file_from_buffer(
        Bucket=bucket,  # 要上传桶的名称
        Body=file_object,  # 本地文件路径
        Key=key,  # 上传到桶之后的文件名

    )

    # https://zhao-1304881545.cos.ap-chengdu.myqcloud.com/p1.png
    # 将图片的路径返回
    return "https://{}.cos.{}.myqcloud.com/{}".format(bucket, region, key)


# 删除文件
def delete_file(bucket, region, key):
    secret_id = settings.COS_SECRET_ID  # 替换为用户的 secretId
    secret_key = settings.COS_SECRET_KEY  # 替换为用户的 secretKey

    config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key)
    # 2. 获取客户端对象
    client = CosS3Client(config)

    #  删除文件
    client.delete_object(
        Bucket=bucket,  # 要上传桶的名称
        Key=key,  # 上传到桶之后的文件名

    )


# 检查文件
def check_file(bucket, region, key):
    secret_id = settings.COS_SECRET_ID  # 替换为用户的 secretId
    secret_key = settings.COS_SECRET_KEY  # 替换为用户的 secretKey

    config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key)
    # 2. 获取客户端对象
    client = CosS3Client(config)
    #  检查文件
    data = client.head_object(
        Bucket=bucket,  # 要上传桶的名称
        Key=key,

    )
    return data


# 批量删除文件
def delete_file_list(bucket, region, key_list):
    secret_id = settings.COS_SECRET_ID  # 替换为用户的 secretId
    secret_key = settings.COS_SECRET_KEY  # 替换为用户的 secretKey

    config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key)
    # 2. 获取客户端对象
    client = CosS3Client(config)
    objects = {
        "Quiet": "true",
        "Object": key_list
    }
    #  删除文件
    client.delete_objects(
        Bucket=bucket,  # 要上传桶的名称
        Delete=objects,

    )


# 生成临时凭证
def credential(bucket, region):
    from sts.sts import Sts
    config = {
        # 临时密钥有效时长，单位是秒（30分钟=1800秒）
        'duration_seconds': 1800,
        # 固定密钥 id
        'secret_id': settings.COS_SECRET_ID,
        # 固定密钥 key
        'secret_key': settings.COS_SECRET_KEY,
        # 换成你的 bucket
        'bucket': bucket,
        # 换成 bucket 所在地区
        'region': region,
        # 这里改成允许的路径前缀，可以根据自己网站的用户登录态判断允许上传的具体路径
        # 例子： a.jpg 或者 a/* 或者 * (使用通配符*存在重大安全风险, 请谨慎评估使用)
        'allow_prefix': '*',
        # 密钥的权限列表。简单上传和分片需要以下的权限，其他权限列表请看 https://cloud.tencent.com/document/product/436/31923
        'allow_actions': [
            'name/cos:PostObject',
            # 'name/cos:DeleteObject',
            # "name/cos:UploadPart",
            # "name/cos:UploadPartCopy",
            # "name/cos:CompleteMultipartUpload",
            # "name/cos:AbortMultipartUpload",
            "*",
        ],

    }

    sts = Sts(config)
    result_dict = sts.get_credential()
    return result_dict  # 包含临时凭证


# 删除桶
def delete_bucket(bucket, region):
    """删除桶"""
    secret_id = settings.COS_SECRET_ID  # 替换为用户的 secretId
    secret_key = settings.COS_SECRET_KEY  # 替换为用户的 secretKey

    config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key)
    # 2. 获取客户端对象
    client = CosS3Client(config)
    # part_objects = client.list_objects(bucket)
    # contents = part_objects.get("Contents")
    # print(contents)
    # [{'Key': '10、用户消费记录分析', 'LastModified': '2021-02-02T06:08:36.000Z', 'ETag': '"61f78cd7f45e78fe1fe1102eef2a2543"',
    #   'Size': '10067', 'Owner': {'ID': '1304881545', 'DisplayName': '1304881545'}, 'StorageClass': 'STANDARD'},

    try:
        # 1. 找到桶中所有的文件,并删除；每次最多返回1000个，所以要循环
        while True:
            part_objects = client.list_objects(bucket)
            contents = part_objects.get("Contents")
            # 已经获取不到值了，循环结束条件
            if not contents:
                break
            # 批量删除
            objects = {
                "Quiet": "true",
                "Object": [{"Key": item["Key"]} for item in contents]
            }
            client.delete_objects(bucket, objects)
            # 拿到最后一个，判断是否别截断了
            if part_objects["IsTruncated"] == "false":
                break

        # 2. 找到碎片&删除,
        while True:
            part_uploads = client.list_multipart_uploads(bucket)
            uploads = part_uploads.get("Upload")
            if not uploads:
                break
            for item in uploads:
                client.abort_multipart_upload(bucket, item["Key"], item["UploadId"])

            if part_uploads["IsTruncated"] == "false":
                break
        # 3. 删除桶
        client.delete_bucket(bucket)
    except CosServiceError as e:
        pass
